<?php
/**
 * 前台订单控制器
 * @version 2014100714
 * @author Max.Yu <max@jipu.com>
 */

namespace Home\Controller;

class OrderController extends HomeController{

  private $Order;

  public function _initialize(){
    parent::_initialize();
    //跳过验证登录
    $jump_loginlist = array('info');
    if(!in_array(ACTION_NAME, $jump_loginlist)){
      parent::login();
    }
    //实例化订单模型
    $this->Order = D('Order');
  }

  /**
   * 订单首页
   * @param $item_ids 商品id，逗号分隔
   * @param $buynow 是否立即购买
   * @author Max.Yu <max@jipu.com>
   */
  public function index($item_ids = null, $buynow = 0){
    //购物车cookie加入
    $cart = cookie('__cart__');
    if($cart){
      D('Cart')->addCartCookie();
    }
    $map['uid'] = UID;
    if($item_ids){
       //TODO:去除秒杀产品
        $map['id'] = array('IN', $item_ids);
       //购物车ID
        $cart_ids = $item_ids;
    }
    $data = array();

    if($buynow == 1){
      //直接购买
      $buynow_cookie = cookie('__buynow__');
      if(empty($buynow_cookie)){
        redirect(U('Member/index'));
      }
      $data['items'] = array(unserialize($buynow_cookie));

      //直接购买查询复购优惠信息 start 20170504
      $dis_prices = array();
      foreach($data['items'] as $key => &$value){
        //复购优惠金额
        if(!in_array($value['item_id'], $dis_prices)){
          $dis_price = A('Fugou', 'Event')->getDisPriceByUser($value['item_id'], UID);
        }else{
          $dis_price = $dis_prices[$value['item_id']];
        }
        $value['dis_price'] = $dis_price;
        $value['price'] = sprintf('%.2f', $value['price'] - $dis_price);
        $value['subAmount'] = sprintf("%.2f", $value['quantity'] * $value['price']);
      }
      $cart_ids = '';
      //直接购买查询复购优惠信息 end 20170504
      $seckill = A('Seckill', 'Event')->getInfo($data['items'][0]['item_id']);
      //属于秒杀商品
      if($seckill){
          //商品按店铺分组
          if($data['items']){
              $data['items'] = D('Cart')->formatByStore($data['items']);
          }
         session('order_commit_item',$data['items']);
          if($seckill['stime'] > NOW_TIME){
              $this->error('活动未开始');
          }
          if($seckill['etime'] <= NOW_TIME){
              $this->error('活动已结束');
          }
          if($seckill['item_stock'] < $data['items'][0]['quantity']){
              $this->error('库存不足');
          }
          R('Seckill/order');
          exit();
      }
    }else{
      //购物车下单
      $field = 'item_id, supplier_id,store_id, item_code, name, number, spec, price, thumb, quantity, weight,freight,transport_id';
      $data['items'] = D('Cart')->lists($map, $field, 'field(item_id,'.$item_ids.')');
    }
    $item_ids_arr = get_sub_by_key($data['items'], 'item_id');
    $item_ids = arr2str($item_ids_arr);
    //商品按店铺分组
    if($data['items']){
        $data['items'] = D('Cart')->formatByStore($data['items']);
    }
    $order_event = A('Order', 'Event');
    //获取当前用户购物车优惠信息
    $order_info= $order_event->getInfo($item_ids,  $cart_ids, $buynow == 1);
    //获取当前用户购物车统计信息
    $order_count = $order_event->doCountNew($item_ids, $cart_ids, $buynow == 1);
    //获取购物车中属于第二件折扣的item_id(array)
    $second_pieces_item = $order_event->getSecondPiecesItemIds($data['items']);
    if($second_pieces_item){
      $second_pieces_item_ids = array_column($second_pieces_item, 'item_id');
      foreach($data['items'] as $k => $v){
        foreach($v['item'] as $key => $value){
          if(in_array($value['item_id'], $second_pieces_item_ids) && ($value['quantity'] >= 2)){
            $data['items'][$k]['item'][$key]['quantity'] = 2;
            $second_price = $data['items'][$k]['item'][$key]['price'] * $second_pieces_item[$data['items'][$k]['item'][$key]['item_id']]['discount'];
            $data['items'][$k]['item'][$key]['subAmount'] = sprintf("%.2f", $data['items'][$k]['item'][$key]['price'] + $second_price);
            $data['items'][$k]['item'][$key]['discount_name'] = $second_pieces_item[$data['items'][$k]['item'][$key]['item_id']]['name'];
          }
        }
      }
    }
    //商品列表为空，跳回购物车
    if(empty($data['items'])){
      $this->redirect('Cart/index');
    }
    session('order_commit_item',$data['items']);
    //获取当前用户收货地址信息
    $maps = array(
        'uid'     => UID,
        'item_id' => $item_ids
      );
    $receiver = D('Receiver')->lists($maps);
    //获取默认收货地址
    $receiver_id = I('get.receiver_id');
    if($receiver_id){
      $data['default_receiver'] = D('Receiver')->detail(array('id' => $receiver_id));
    }else{
      $has_default = D('Receiver')->detail(array('uid'=>UID,'is_default'=>1));
      $data['default_receiver'] = $has_default ? $has_default : $receiver[0];
    }

    //根所收货ID获取物流
     $data['delivery']=$this->getDeliveryByArea($data['default_receiver']['id']);

    //获取当前用户所有可用礼品卡
    $data['cards']['lists'] = $order_event->getShopCardList();
    $data['cards']['total'] = count($data['cards']['lists']);

    if($data['default_receiver']['district'])$this->city = $data['default_receiver']['city'];
    session('sel_address_urlfrom', SITE_URL.$_SERVER['REQUEST_URI']);
    //发票类型
    $invoiceType = C('INVOICE_TYPE');
    //发票内容
    $invoiceContent = C('INVOICE_CONTENT');

    /*==========================多商铺单独处理================================*/

    foreach (array_keys($order_info['store']) as $store_id) {
      
      //不同店铺满减信息
      $data['items'][$store_id]['manjian'] = $order_event->getManjianRule($store_id);
      
      //不同店铺优惠券信息
      $coupon_list = $order_event->getStoreCouponList($data['items'],$order_count,$store_id);

      $data['items'][$store_id]['coupon_lists'] = $coupon_list;
      
      $data['items'][$store_id]['coupon_total'] = count($coupon_list);
    
    }
    /*==========================多商铺单独处理================================*/

    if (count($data['delivery']) == 1) {
        $delivery_arr = array_values($data['delivery']);
        $this->delivery_fee = $delivery_arr[0]['price'];
    }else{
        $this->delivery_fee = 0;
    }
    //个人可用余额重定义
    $maps = array(
        'uid'    => UID,
        'type'   => 'sdp_order',
        'flow'   => 'in',
        'status' => 0
      );
    $union_finance = M('Finance')->where($maps)->sum('amount') ?: 0;
    $user_union_finance = (float)($this->member['finance']) - $union_finance;
    $this->finance =  $user_union_finance;

    $this->item_ids = $item_ids;
    $this->cart_ids = $cart_ids;
    $this->receiver = $receiver;
    $this->order_info = $order_info;
    $this->order_count = $order_count;
    $this->data = $data;
    $this->invoiceType = $invoiceType;
    $this->invoiceContent = $invoiceContent;
    $this->buynow = $buynow;
    $this->meta_title = '确认订单';
    $this->display();
  }

  /**
   * 根据地址获取物流价格
   */
  public function getDeliveryByArea($receiver_id=-1,$items=array()){

      if(!count($items))$items=session('order_commit_item');
      $receiver=D('Receiver')->detail(array('id' => $receiver_id));
      if(!$receiver){
          $receiver=array(
              'city'=>I('city',0),
              'district'=>I('district',0),
              'province'=>I('province',0)
          );
      }
      //区域价格
      if (C('START_POSITION')) {
        foreach ($items as $key => $value) {
          foreach ($value['item'] as $k => $v) {
            $items[$key]['item'][$k]['price'] = D('Order')->getItemPrice($v['item_id'] , $v['item_code'], true , I('post.city') );
            //第二件折扣
            $second_discount = D('Order')->getSecondItemsPrice($v['item_id']);
            if ($second_discount > 0 && $v['quantity'] >=2 ) {
              $items[$key]['item'][$k]['subAmount'] = $items[$key]['item'][$k]['price'] + $items[$key]['item'][$k]['price']*$second_discount;
            }else{
              $items[$key]['item'][$k]['subAmount'] = $items[$key]['item'][$k]['price'] * $v['quantity'];
            }
          }
        }
      }

      $delivery=array();
      foreach ($items as $store){
          $delivery[$store['store_id']]['freight']['delivery_price']=0;
          $delivery[$store['store_id']]['total_price']=0;
          foreach ($store['item'] as $item){
              if(empty($item['transport_id'])){
                  //固定运费直接递增
                  $delivery[$store['store_id']]['freight']['delivery_price']+=$item['freight'];
              }else{
                  //用收货地址的省市区的值匹配物流表。
                  $now_transport=M('TransportExtend')->where('(FIND_IN_SET('.$receiver['city'].',`city`) OR FIND_IN_SET('.$receiver['district'].',`city`) OR FIND_IN_SET('.$receiver['province'].',`city`)) AND transport_id='.$item['transport_id'])->find();
                  if(!$now_transport)$now_transport=M('TransportExtend')->where('(ISNULL(city) OR city="") AND transport_id ='.$item['transport_id'])->find();
                  $delivery[$store['store_id']]['transport'][$now_transport['id']]['quantity']+=$item['quantity'];
                  $delivery[$store['store_id']]['transport'][$now_transport['id']]['weight']+=$item['weight'];
                  $delivery[$store['store_id']]['transport'][$now_transport['id']]['transport']=$now_transport;
              }
              //订单总金额
              $delivery[$store['store_id']]['total_price']+=$item['price']*$item['quantity'];
              //各个商户订单总金额
              $delivery[$store['store_id']]['subAmount'] += (float)$item['subAmount'];
          }
      }
      $redelivery=array();
      foreach ($delivery as $k=>$v){
          $free_price=M('Store')->where(array('store_id'=>$k))->getField('free_price');
          $jian = get_store_manjian_new($k,$v['subAmount']);
          if($free_price>0 && $v['total_price']>=$free_price){
              $redelivery[$k]=array(
                  'store_id'=>$k,
                  'msg'=>'0.00元',
                  'price'=>0.00,
                  'shop_amount'=>($v['subAmount'] - $jian),
                  'jian'=>$jian,
                  'total_amount'=>number_format(($v['subAmount'] - $jian),2,'.','').'元'
              );
          }else{
              $price=$v['freight']['delivery_price'];
              foreach ($v['transport'] as $transport){
                  if($transport['transport']['price_type']==1){
                      $price+=$transport['transport']['express_postage'];
                      if($transport['quantity']>$transport['transport']['express_start'])$price+=ceil(($transport['quantity']-$transport['transport']['express_start'])/$transport['transport']['express_plus'])*$transport['transport']['express_postageplus'];
                  }
              }
              $redelivery[$k]=array(
                  'store_id'=>$k,
                  'msg'=>number_format($price,2).'元',
                  'price'=>$price,
                  'shop_amount'=>($v['subAmount'] + $price - $jian),
                  'jian'=>$jian,
                  'total_amount'=>number_format(($v['subAmount'] + $price - $jian),2,'.','').'元'
              );
          }
      }
      if($receiver_id<0){
          print_r(json_encode(array('status'=>1,'data'=>$redelivery,'store_num'=>count(array_keys($delivery)))));
      }else{
          return $redelivery;
      }
  }

  /**
   * 动态获取店铺满减信息
   * @param  [type] $store_id [description]
   * @return [type]           [description]
   */
  public function getStoreManjianInfo(){

    $store_id = I('post.store_id');
    $buynow = I('post.buynow');
    $info = get_store_manjian($store_id,true,$buynow);
    $this->ajaxReturn($info);
  }
  /**
   * 订单明细
   * @author Max.Yu <max@jipu.com>
   */
  public function detail(){
    $map['uid'] = UID;
    $map['order_sn'] = I('get.order_sn');
    $data = $this->Order->detail($map);
    if(empty($data['items'])){
      $this->error('订单不存在！');
    }

    if($data['reship_info']){
      $data['reship_info_text'] = json_decode($data['reship_info'], true);
    }
    if(!empty($data['invoice_title'])){
      $tempdata = explode('&nbsp',$data['invoice_title']);
      $data['invoice_des']['发票类型']   = $tempdata[0];
      switch ($tempdata[0]) {
        case '增值税发票':
          $data['invoice_des']['单位名称']     = $tempdata[1];
          $data['invoice_des']['纳税人识别码'] = $tempdata[2];
          $data['invoice_des']['注册地址']=$tempdata[3];
          $data['invoice_des']['注册电话']=$tempdata[4];
          $data['invoice_des']['开户银行']=$tempdata[5];
          $data['invoice_des']['银行账户']=$tempdata[6];
          $data['invoice_des']['发票内容']=$tempdata[7];
          break;
        default:
          $data['invoice_des']['发票抬头']  = $tempdata[1];
          $data['invoice_des']['发票内容']  = $tempdata[2];
          break;
      }
    }
    if($data['o_status'] == 0){
      $data['memo'] = handlememo($data['memo']);
    }else{
      if(!empty($data['memo'])){
        //供应商变更为商户
        $store_list = handleother($data['memo']);
        unset($data['memo']);
        foreach ($store_list as $key => $value) {
          $name = $key == 0 ? C('WEB_SITE_TITLE') : get_store_text($key);
          $data['memo'][$name] = $value;
          if (empty($value)) {
            unset($data['memo'][$name]);
          }
        }
      } 
    }

    $store_ids_arr = explode(',',$data['store_ids']);
    //店铺区分开来
    foreach ($store_ids_arr as $key => $value) {
      $store_item_list[$key] = M('OrderItem')->where(array('order_id'=>$data['id'],'store_id'=>$value))->getField('item_id',true);
    }

    //查询每个商品的店铺ID
    foreach ($data['items'] as $key => $value) {
      $data['items'][$key]['store_id'] = M('Item')->where('id='.$value['item_id'])->getField('store_id');
    }

    //重组数组
    $data['ItemList'] = arrKeyChange($data['items'],'store_id',false);

    //合并数组
    foreach ($data['ItemList'] as $key => $value) {
      $data['store_list']['store'][$key] = $value;
      $data['store_list']['delivery'][$key] = M('StoreOrder')->where(array('store_ids'=>$key,'order_sn'=>$data['order_sn']))->find();
    }
    
    //物流
    foreach ($data['store_list']['delivery'] as $key => $value) {
      $data['store_list']['Ship'][$key] = M('ship')->where(array('order_id'=>$value['id']))->find();
    }
    
    $this->data = $data;
    $this->meta_title = '订单详情';
    $this->display();
  }

  /**
   * 订单预览
   * @param $order_sn 订单编号
   * @param $order_id 订单ID
   * @author Max.Yu <max@jipu.com>
   */
  public function preview($order_sn = '', $order_id = ''){
    if(empty($order_sn) && empty($order_id)){
      $this->error('订单编号不能为空！');
    }
    if($order_sn){
      $map['order_sn'] = $order_sn;
    }
    if($order_id){
      $map['id'] = $order_id;
    }

    $data = $this->Order->detail($map);
    $order = R('Pay/checkOrder');
    if(empty($data)){
      $this->error('订单不存在！');
    }
    if($data['o_status'] != 0){
      $this->error('该订单不可付款！');
    }
    if(!empty($data['invoice_title'] )){
      $tempdata = explode('&nbsp',$data['invoice_title']);
      $data['invoice_des']['发票类型']   = $tempdata[0];
      switch ($tempdata[0]) {
        case '增值税发票':
          $data['invoice_des']['单位名称']     = $tempdata[1];
          $data['invoice_des']['纳税人识别码'] = $tempdata[2];
          $data['invoice_des']['注册地址']=$tempdata[3];
          $data['invoice_des']['注册电话']=$tempdata[4];
          $data['invoice_des']['开户银行']=$tempdata[5];
          $data['invoice_des']['银行账户']=$tempdata[6];
          $data['invoice_des']['发票内容']=$tempdata[7];
          break;
        default:
          $data['invoice_des']['发票抬头']  = $tempdata[1];
          $data['invoice_des']['发票内容']  = $tempdata[2];
          break;
      }
    }
    if(is_weixin()){
      $this->assign('weixin',1);
    }
    $data['memo'] = handlememo($data['memo']);
    $this->data = $data;
    $this->meta_title = '订单已生成';
    $this->display();
  }
  /**
   * 支付成功后提示信息
   * @author Max.Yu <max@jipu.com>
   */
  public function info(){
    $order_id = I('get.order_id');
    $order_sn = I('get.order_sn');
    $order_type = I('get.order_type', 'item_order');

    //众筹订单跳转到doing
    if($order_type == 'crowdfunding_order'){
      if($order_id){
        $map['id'] = $order_id;
      }elseif($order_sn){
        $map['pay_id'] = $order_sn;
      }else{
        $map[] = '1=0';
      }
      $c_line = M('CrowdfundingUsers')->where($map)->find();
      if($c_line){
        $url = U('Crowdfunding/doing', array('id' => $c_line['crowdfunding_id'], 'oid' => $c_line['order_id']));
        redirect($url);
      }
      //红包订单跳转到doing
    }else if($order_type == 'redpacket_order'){
      if($order_id){
        $map['id'] = $order_id;
      }elseif($order_sn){
        $map['order_sn'] = $order_sn;
      }else{
        $map[] = '1=0';
      }
      $c_line = M('Redpacket')->where($map)->find();
      if($c_line){
        $url = U('Redpacket/send', array('id' => $c_line['id']));
        redirect($url);
      }
    //拼团订单
    }else if($order_type == 'join_order'){
        $url = U('Join/joinOrder');
        redirect($url);
    }
    $order_id ? $map['id'] = $order_id : $map['order_sn'] = $order_sn;
    //判断订单状态
    if(M('Order')->where($map)->getField('o_status') !== '200'){
      $this->error('订单支付失败，钱已充入余额！', U('Member/order'));
    }
    $this->display();
  }

  /**
   * 提交订单
   * @author Max.Yu <max@jipu.com>
   * @version 2015083115 Justin Rebuild
   */ 
  public function add(){
    //用户扫描带参数的二维码ID
    $union_id = $this->user['from_union_id'];
    $union_id && ($data['union_id'] = $union_id) && ($data = array_merge($data, $_POST));

    $result = $this->Order->update($data, I('post.buynow') == 1);

    if($result){
      $this->success('订单已生成，请付款', U('Order/preview', array('order_id' => $result)));
    }else{
      $this->error($this->Order->getError() ? $this->Order->getError() : '订单提交失败！', U('/'));
    }
  }

  /**
   * 提交订单
   * @author Max.Yu <max@jipu.com>
   */
  public function submit(){
    $result = false;
    $id = I('id');
    $quantity = intval(I('quantity'));
    if(empty($id)){
      $result = array(
        'status' => 'error',
      );
    }

    $add = $this->Cart->addCart($id, $quantity, UID);
    if($add){
      $result = array(
        'status' => 'success',
      );
    }else{
      $result = array(
        'status' => 'error',
        'info' => $info,
      );
    }
    $this->ajaxReturn($result);
  }

  /**
   * 修改订单
   * @author Max.Yu <max@jipu.com>
   */
  public function update(){
    $id = intval(I('request.id'));
    $data['quantity'] = intval(I('quantity'));
    $data['uid'] = UID;
    $update = $this->Cart->updateCart($data);
    $total = $this->Cart->doCount();
    if($update){
      $result = array(
        'status' => 'success',
        'total' => $total,
      );
    }else{
      $result = array(
        'status' => 'error',
        'total' => $total,
      );
    }
    $this->ajaxReturn($result);
  }

  /**
   * 设置订单状态
   * @author Justin <justin@jipu.com>
   */
  public function setStatus($order_id = null, $type = 'cancel'){
    if(IS_POST){
      if(empty($order_id)){
        $this->error('订单ID不能为空！');
      }

      //订单号
      $order_sn = getOrderSnByOrderId($order_id);

      $text = array(
        'cancel' => '取消',
        'recycle' => '删除',
        'delete' => '删除',
        'restore' => '还原'
      );
      switch($type){
        case 'cancel' :
          $res = M('Order')->where(array('id' => $order_id, 'uid' => UID))->setField('o_status', -1);
          M('StoreOrder')->where(array('order_sn'=>$order_sn,'uid'=>UID))->setField('o_status',-1);
          break;
        case 'recycle' :
          $new_status = 2;
          break;
        case 'delete' :
          $new_status = 3;
          break;
        case 'restore' :
          $new_status = 1;
          break;
      }

      $new_status && $res = M('Order')->where(array('id' => $order_id, 'uid' => UID))->setField('status', $new_status);
      //商户订单状态同步改变
      M('StoreOrder')->where(array('order_sn'=>$order_sn,'uid'=>UID))->setField('status', $new_status);
      
      if($res){
        $this->success('订单'.$text[$type].'成功！');
      }else{
        $this->error('订单'.($text[$type] ? $text[$type] : '处理').'失败！');
      }
    }else{
      $this->error('非法请求');
    }
  }

  /**
   * 确认收货
   * @author Max.Yu <max@jipu.com>
   */
  public function confirm(){
    $order_id = I('post.order_id');
    
    $count = A('Order','Event')->checkOrderCount($order_id);

    if ($count == 0) {
      $this->error('订单不存在');
    }

    $order = M('StoreOrder')->where(array('id' => $order_id, 'uid' => UID))->find();

    $old_id = M('Order')->where('order_sn='.$order['order_sn'])->getField('id');

    //已发货，未确认收货
    if( in_array($order['o_status'],array(201,405))){
      $save_data = array(
        'o_status' => 202,
        'complete_time' => NOW_TIME,
      );
      if ($order['o_status'] == 405) {
        $save_data['refuse_message'] = '';
      }

      $res = M('StoreOrder')->where('id='.$order['id'])->save($save_data);

      $store_count = A('Order','Event')->checkOrderStatusCount($save_data,$order['order_sn'],$count);
      
      //平台订单状态同步判断
      if ($count == 1 || (($count-1) == $store_count) ) {
        M('Order')->where('order_sn='.$order['order_sn'])->save($save_data);
      }

      if($res){
        //推广联盟返现时机 订单完成时返现 暂时屏蔽
        if( C('DIS_ORDERSTATUS') == 0){
          distribute($old_id ,UID, $order['item_ids'] ,$order_id);
        }
        $this->success('确认收货成功');
      }else{
        $this->error('确认收货失败');
      }
    }else{
      $this->error('当前订单状态，不允许确认收货');
    }
  }

  /**
   * 申请退款
   * @author Max.Yu <max@jipu.com>
   */
  public function refund(){
    $order_id = I('post.order_id');

    $count = A('Order','Event')->checkOrderCount($order_id);

    if ($count == 0) {
      $this->error('订单不存在');
    }

    $order = M('StoreOrder')->where(array('id' => $order_id, 'uid' => UID))->find();

    //未发货、已发货、已收货都可以申请退款
    if(in_array($order['o_status'], array(200, 201, 202, 405))){
      
      //后台进行配置
      $refund_order_day = NOW_TIME - (C('MAX_REFUND_CASH_DAY')*24*3600);
      if($order['o_status'] == 202 && ($order['complete_time'] < $refund_order_day)){
        $this->error('订单已超过退款期限');
      }
      $save_data = array(
        'o_status' => 300,
      );
      //以前申请售后拒绝，再次申请，拒绝理由置空
      if ($order['o_status'] == 405) {
        $save_data['refuse_message'] = '';
      }

      //商户订单状态修改
      $res = M('StoreOrder')->where('id='.$order['id'])->save($save_data);

      $store_count = A('Order','Event')->checkOrderStatusCount($save_data,$order['order_sn']);
      
      //平台订单状态同步判断
      if ($count == 1 || ($count == $store_count ) ) {

        M('Order')->where('order_sn='.$order['order_sn'])->save($save_data);
      }
      
      if($res){
        $this->success('申请成功，待管理员处理');
      }else{
        $this->error('申请失败');
      }
    }else{
      $this->error('当前订单状态，不允许申请退款');
    }
  }

  /**
   * 取消退款申请
   */
  public function unrefund(){
    $order_id = I('post.order_id');
    
    $count = A('Order','Event')->checkOrderCount($order_id);

    if ($count == 0) {
      $this->error('订单不存在');
    }

    $order = M('StoreOrder')->where(array('id' => $order_id, 'uid' => UID))->find();

    if($order['o_status'] == 300){
      $to_status = 0;
      //已支付
      $order['payment_time'] > 0 && $to_status = 200;
      //已发货
      $order['shipping_time'] > 0 && $to_status = 201;
      //已完成
      $order['complete_time'] > 0 && $to_status = 202;

      //商户处理业务操作
      $res = M('StoreOrder')->where('id='.$order['id'])->setField('o_status', $to_status);

      $store_count = A('Order','Event')->checkOrderStatusCount(array($to_status),$order['order_sn']);

      //平台订单状态同步判断
      if ($count == 1 || ($count == $store_count )) {
        
        M('Order')->where('order_sn='.$order['order_sn'])->setField('o_status', $to_status);
      }
      
      if($res){
        $this->success('退款申请已取消');
      }else{
        $this->error('操作失败了！');
      }
    }else{
      $this->error('错误的状态操作！');
    }
  }

  /**
   * 退款物流
   * @author Max.Yu <max@jipu.com>
   */
  public function reShip(){
    $order_id = I('order_id');
    
    $count = A('Order','Event')->checkOrderCount($order_id);

    if ($count == 0) {
      $this->error('订单不存在');
    }

    $order = M('StoreOrder')->where(array('id' => $order_id, 'uid' => UID))->find();

    if($order['o_status'] == 301){
      //退货信息保存
      if(IS_POST){
        $company_name = I('post.company_name', '', trim);
        $ship_number = I('post.ship_number', '', trim);
        empty($company_name) && $this->error('请输入快递公司名称！');
        empty($ship_number) && $this->error('请输入快递单号！');
        $reship_info = array(
          'company_name' => $company_name,
          'ship_number' => $ship_number,
          'reship_time' => time()
        );
        $save_data = array(
          'o_status' => 302,
          'reship_info' => json_encode($reship_info),
        );

        $res = M('StoreOrder')->where('id='.$order['id'])->save($save_data);

        $store_count = A('Order','Event')->checkOrderStatusCount($save_data,$order['order_sn'],$count);

        //平台信息同步        
        if ($count == 1 || ($count == $store_count) ) {
          M('Order')->where('order_sn='.$order['order_sn'])->save($save_data);
        }

        if($res){
          $this->success('保存成功，待管理员退款', U('Order/detail', array('order_sn' => $order['order_sn'])));
        }else{
          $this->error('保存失败');
        }
      }else{
        
        $this->order = $order;
        
        //获取物流信息
        $this->delivery = C('EXPRESS_LISTS');
        
        $this->meta_title = '退货物流';
        
        $this->display();
      }
    }else{
      if($order['reship_info']){
        $info_arr = json_decode($order['reship_info'], true);
        $this->data = $info_arr;
        $this->display('reShipDelivery');
      }else{
        die('当前订单状态，不允许填写退款信息');
      }
    }
  }

  /**
   * 获取物流动态信息
   * @author Max.Yu <max@jipu.com>
   */
  public function getDelivery($order_id = 0){
    $data = M('Ship')->getByOrderId($order_id);
    $this->data = $data;
    $this->display();
  }

  /**
   * 获取订单详情页面
   * @author buddha <[email address]>
   * @param  [type] $order_id     [description]
   * @param  [type] $payment_type [description]
   * @return [type]               [description]
   */
  public function getOrderDetail($order_id,$payment_type,$device_type=''){
      if(!$order_id){
          $this->error('订单编号不能为空！');
      }
      if($order_id){
          $map['id'] = $order_id;
      }
      $order = $this->Order->detail($map);
      $data['orderid'] = $order_id;
      $order_type = $order['order_type']['name'] . '_order';
      //设置商品订单支付方式 微信APP支付特殊处理 buddha
      if ($payment_type == 'wechatpay') {
        $payment_type = 'wechatAppPay';
      }
      //设置商品订单支付方式
      A('pay','Event')->updateOrderPayment($order_id, $payment_type, $order_type);
      if($payment_type == 'wechatAppPay'){    //微信支付
          //统一下单接口，返回预支付id
          //预付订单号
          $prepay_id = A('pay','Event')->getPrePayId($data,$order_type,"APP");
          //var_dump($unifiedOrder);
          $config = C("WECHATAPPPAY");
          //获取appid
          $appid = $config['app_id'];
          //获取商户号
          $mch_id = $config['mch_id'];
          //二次签名
          import('Org.Wechat.Pay.WxPayPubHelper', '', '.php');
          $UnifiedOrder_pub = new \UnifiedOrder_pub("APP");
          $res = array();
          $res['appid'] = $appid;
          $res['noncestr'] = $UnifiedOrder_pub->createNoncestr();//随机字串
          $res['package'] = 'Sign=WXPay';
          $res['partnerid'] = $mch_id;
          $res['prepayid'] = $prepay_id;
          $res['timestamp'] = time();
          $sign = $UnifiedOrder_pub->getSign($res);   //签名
          $res['sign'] = $sign;
          $res['pay_type'] = "wechatpay";
      }elseif($payment_type == 'alipaywap'){  //支付宝支付
          //获取订单商品名称
          $item_names = D('Item')->getItemNamesForPay($order['item_ids']);
          //订单描述
          $subject = '网站购物-'.$item_names;
          //设置支付宝请求参数
          $payment_config = A('pay','Event')->setAppPaymentConfig($payment_type, $order_type);
          //请求方式：新接口
          $str = $this->aliPayWapNew($payment_config,$order,$subject,$device_type);
          $res = array(
                'orderInfo' => $str,
                'pay_type' => 'alipaywap'
            );
      }
      echo json_encode($res);
  }

  /**
   * 支付宝APP支付 <新的接口:alipay.trade.app.pay>
   * @author buddha <buddha@jipu.com>
   * @param  [type] $config    [description]
   * @param  [type] $order     [description]
   * @param  [type] $item_desc [description]
   * @return [type]            [description]
   */
  private function aliPayWapNew($config,$order,$item_desc,$app_type){
    //支付宝APP支付业务请求参数
    $data = array(
        'body'           => $item_desc,//商品详情
        'subject'        => $item_desc,//商品标题
        'out_trade_no'   => $order['order_sn'],//商户网站唯一订单号
        'total_amount'   => $order['total_amount'],//订单总金额，单位为元
        'product_code'   => 'QUICK_MSECURITY_PAY',//销售产品码，商家和支付宝签约的产品码，为固定值
      );
    //支付宝APP支付业务请求参数json格式
    $json = "{\"body\":\"".$item_desc."\",".
             "\"subject\":\"".$item_desc."\",".
             "\"out_trade_no\":\"".$order['order_sn']."\",".
             "\"timeout_express\":\"30m\",".
             "\"total_amount\":\"".$order['total_amount']."\",".
             "\"product_code\":\"QUICK_MSECURITY_PAY\"}";
    //支付宝公共参数
    $parameters = array(
        'app_id'        => $config['app_id'],//应用ID
        'method'        => 'alipay.trade.app.pay',//接口名称
        'charset'       => 'utf-8',//请求编码
        'sign_type'     => 'RSA',//签名算法
        'timestamp'     => date('Y-m-d H:i:s'),//请求时间戳
        'version'       => '1.0',//接口版本
        'notify_url'    => $config['notify_url'],// 支付宝服务器主动通知商户服务器里指定的页面http/https路径
        //'biz_content'   => json_encode($data),//业务请求参数的集合
        'biz_content'   => $json,//业务请求参数的集合
      );
    //set_log('alipay_new',$parameters);
    //设置签名
    import('Org.Wechat.Pay.NewAopClient', '', '.php');
    $Client = new \AopClient();
    $paramStr = $Client->getSignContent($parameters);//代签名字符串
    //set_log('alipay_app',$paramStr);
    $parameters['sign'] = $Client->sign($paramStr,$config['private_key_path']);//签名字符串
    set_log('alipay_app',$parameters);
    $encodeStr = $Client->getSignContentUrlencode($parameters);//字符串值进行encode处理
    //set_log('alipay_app',$encodeStr);
    if($app_type == 1){
      $encodeStr = "alipay://alipayclient/?".urlencode(json_encode(array('requestType'=>'SafePay','fromAppUrlScheme'=>'me.shante.www','dataString'=>$encodeStr)));
    }
    
    return $encodeStr;
  }

  /**
   * 支付宝支付 <旧接口:mobile.securitypay.pay>
   * @author buddha <buddha@jipu.com>
   * @param  [type] $config    [description]
   * @param  [type] $order     [description]
   * @param  [type] $item_desc [description]
   * @param  [type] $app_type  [description]
   * @return [type]            [description]
   */
  private function aliPayWap($config,$order,$item_desc,$app_type){
    $parameters = array(
        'service' => 'mobile.securitypay.pay',  //接口名称
        'partner' => $config['partner'], //合作者身份ID
        '_input_charset' => 'UTF-8',            //参数编码字符集
        'notify_url' => $config['notify_url'],  //服务器异步通知页面路径
        'out_trade_no' => $order['order_sn'],       //商户网站唯一订单号
        'subject' => $item_desc,                  //商品名称
        'payment_type' => 1,                    //支付类型
        'seller_id' => $config['partner'],//卖家支付宝账号
        'total_fee' => $order['total_amount'],  //总金额
        'body' => $item_desc,// 商品详情
    );
    //IOS-APP 支付特殊处理
    if ($app_type == 1) {
      $parameters['it_b_pay'] = '30m';
    }
    //设置签名
    import('Org.Wechat.Pay.AopClient', '', '.php');
    $Client = new \AopClient();
    $paramStr = $Client->getSignContent($parameters);
    $parameters['sign'] = $Client->alonersaSign($paramStr,$config['private_key_path']);
    $parameters['sign_type'] = 'RSA'; //签名方式
    //set_log('alipay_old',$parameters);
    if ($device_type == 1) {
      $string = $Client->getSignContentUrlencode($parameters);
      $str = "alipay://alipayclient/?".urlencode(json_encode(array('requestType'=>'SafePay','fromAppUrlScheme'=>'me.shante.www','dataString'=>$string)));
    }else{
      $str = $Client->getSignContentUrlencode($parameters);
    }
    return $str;
  }

}
